package live.zs.excelurltoimg.controller;

import jakarta.servlet.http.HttpServletResponse;
import live.zs.excelurltoimg.service.ExcelHyperlinkToImageService;
import live.zs.excelurltoimg.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author madison
 * {@code @description}
 * {@code @date} 2023/12/16 17:07
 */
@RestController
public class FileUploadController {

    private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
    @Autowired
    private ExcelHyperlinkToImageService excelHyperlinkToImageService;

    @Value("${file.upload.folder}")
    private String uploadedFolder;

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
        String filename = file.getOriginalFilename();

        try {
            // 处理文件 - 这里只是简单地保存
            FileUtils.checkFileExists(uploadedFolder);
            Path path = Paths.get(uploadedFolder + filename);
            Files.write(path, file.getBytes());

            // 解压文件
            String name = FileUtils.getFileNameWithoutExtension(filename);
            String unzipDest = uploadedFolder + "unzip" + File.separator + name + File.separator;
            FileUtils.checkFileExists(unzipDest);
            FileUtils.unzip(uploadedFolder + filename, unzipDest);

            // 处理文件 - 在这里添加你的文件处理逻辑
            String excelFilePath = FileUtils.containsExcelFiles(unzipDest);
            String toExcelFilePath = unzipDest + "img_" + name + ".xlsx";
            log.info("excelFilePath:{}, toExcelFilePath:{}", excelFilePath, toExcelFilePath);
            excelHyperlinkToImageService.convert(excelFilePath, toExcelFilePath, unzipDest);
            return toExcelFilePath;


        } catch (Exception e) {
            throw new RuntimeException("Failed to store file " + filename, e);
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> download(String path, HttpServletResponse response) {

        try {
            // 准备下载
            Resource fileResource = new UrlResource(Paths.get(path).toUri());

            // 对文件名进行URL编码
            String encodedFilename = URLEncoder.encode(fileResource.getFilename(), StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + "\"; filename*=UTF-8''" + encodedFilename);

            if (fileResource.exists() || fileResource.isReadable()) {
                return ResponseEntity.ok()
                        .headers(headers)
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(fileResource);
            } else {
                throw new RuntimeException("Could not read the file!");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
